<template>
  <el-select
    :value="value"
    v-bind="$attrs"
    v-on="$listeners"
    @change="(val) => $emit('change', val)"
  >
    <!-- 继承所有的slot，除了 default -->
    <template :slot="item" v-for="item in Object.keys(this.$scopedSlots)">
      <slot :name="item" />
    </template>
    <!-- 自定义 default 插槽，利用现有 form-generator 动态数据能力 -->
    <el-option
      v-for="item in list"
      :key="item.value"
      :label="item.label"
      :value="item.value"
      :disabled="item.disabled"
    >
    </el-option>
  </el-select>
</template>

<script>
export default {
  name: "UnDSelect",
  inheritAttrs: false,
  modal: {
    prop: "value",
    event: "change",
  },
  props: {
    value: [Number, String],
    // 支持 ['string1', 'string2'] 、[1, 2] 和 [{ label: 'string1', value: 'val1'}] 三种形式
    options: {
      type: Array,
      default() {
        return [];
      },
    },
    props: {
      type: Object,
      default() {
        return {
          label: "label",
          value: "value",
        };
      },
    },
  },
  data() {
    return {
      list: this.setList(this.options),
    };
  },
  watch: {
    options(val) {
      this.list = this.setList(val);
    },
  },
  methods: {
    setList(val) {
      return (val || []).map((item) => {
        if (["string", "number"].includes(typeof item)) {
          return {
            label: item,
            value: item,
          };
        }
        return {
          label: item[this.props.label || "label"],
          value: item[this.props.value || "value"],
        };
      });
    },
  },
};
</script>

<style></style>
